/**
	角色
 */
package dao

import (
	"github.com/jinzhu/gorm"
	"time"
)

type Role struct {
	Rid int `json:"rid" gorm:"column:rid"`
	Title string `json:"title" gorm:"column:title"`
	Rules string `json:"rules" gorm:"column:rules"`
	Desc string `json:"desc" gorm:"column:desc"`
	Ctime int64 `json:"c_time" gorm:"column:c_time"`
	Dtime int64 `json:"d_time" gorm:"column:d_time"`
}

func (r *Role) Create(s map[string]interface{}) (bool,int) {

	var addr Role
	if v,ok := s["title"];ok{
		addr.Title = v.(string)
	}
	if v,ok := s["rules"];ok{
		addr.Rules = v.(string)
	}
	if v,ok := s["desc"];ok{
		addr.Desc = v.(string)
	}

	addr.Ctime = time.Now().Unix()

	err := db.Create(&addr).Error
	b := true
	if err != nil{
		panic(err)
	}
	var id []int
	db.Raw("select LAST_INSERT_ID() as id").Pluck("id", &id)
	return b,id[0]

}
/**
	软删除
 */
func (r *Role) Delete(w map[string]interface{}) bool {

	upd := Role{
		Dtime:time.Now().Unix(),
	}
	err := db.Model(&r).Where(w).Update(upd).Error
	b := true
	if err != nil {
		b = false
	}
	return b

}
/**
	硬删除
 */
func (r *Role) HardDel(w map[string]interface{}) bool {

	err := db.Where(w).Delete(&r).Error
	b := true
	if err !=nil{
		b = false
	}
	return b

}
/**
	更新
 */
func (r *Role) Update(w map[string]interface{},f map[string]interface{}) bool {

	fs := &Role{}
	if v,ok := f["title"];ok{
		fs.Title = v.(string)
	}
	if v,ok := f["rules"];ok{
		fs.Rules = v.(string)
	}
	if v,ok := f["desc"];ok{
		fs.Desc = v.(string)
	}
	err := db.Model(&r).Where(w).Updates(fs).Error
	b := true
	if err != nil{
		b = false
	}
	return b

}
/**
	读取结果集
 */
func (r *Role) Find(w map[string]interface{},page int,pageSize int) ([]*Role,int, error){

	var total int = 0
	var rs []*Role
	// 获取取指page，指定pagesize的记录
	err := db.Where(w).
		Where("d_time = ?",0).
		Limit(pageSize).Offset((page-1)*pageSize).
		Order("rid desc").
		Find(&rs).Error

	// 获取总条数
	db.Model(&r).Where(w).Where("d_time = ?",0).Count(&total)

	if err != nil && err != gorm.ErrRecordNotFound{
		return nil ,0,err
	}
	return rs,total,nil

}
/**
	读取单条记录
 */
func (r *Role) First(w map[string]interface{},f []string) (bool,*Role){

	err := db.Select(f).Where("d_time = ?","").Where(w).First(&r).Error

	if err !=nil{
		return false,nil
	}
	return true,r

}
var RoleDao = &Role{}
